/*
 * EPA.js
 */
window.uam = window.uam || {};
uam.lsnr = uam.lsnr || {};
uam.task = uam.task || {};
uam.vld = uam.vld || {};

uam.lsnr.gotoPage = function(url) {
	//mstrWeb?pg=PACnf
	location.href = url;
}
/**************************************
 * Listener
 **************************************/
uam.lsnr.openIAMDialog = function(isOpen) {
	$(".IAMDialog").css({display:"block", position:"absolute", left:"150px", top:"150px", "z-index":"100"});
	if (isOpen) {
		$(".IAMDialog").show();
	} else {
		$(".IAMDialog").hide();
	}
}

uam.UTIL = {
	winCls:function(origId, trgId){
		$("#"+trgId).css({display:"none"});
	}
}

uam.MPCB = {
	isChecked:function(cbId, cntId){
		if($("#"+cbId).prop("checked")){
			$("#"+cntId).css({display:"block"});
		}else{
			$("#"+cntId).css({display:"none"});
		}
	}
}

uam.MARC = {
	isShdRpt:function(obj, id){
		if(obj.value=='yes' || obj.value=="View"){
			$("#"+id).css({display:"block", position:"absolute", left:"70px", top:"710px", "z-index":"100"});
		}else if(obj.value=='no'){
			$("#"+id).css({display:"none"});
		}else{
			throw new Error(obj.value+' radio is not found!');
		}
	},

	isDataAcce:function(obj, id){
		if(obj.value=='rgCt' || obj.value=="View"){
			$("#"+id).css({display:"block", position:"absolute", left:"70px", top:"710px", "z-index":"100"});
		}else if(obj.value=='global'){
			$("#"+id).css({display:"none"});
		}else{
			throw new Error(obj.value+' radio is not found!');
		}
	}
}

uam.productChanged = function(event) {
	var prodList = [
		{ name:"MARC", 		value:1, checkboxId : "marcCheckBox", 	tipId : "marcTip",   contentClass:"marcContent"},
		{ name:"Dashboard", value:2, checkboxId : "servDOECheckBox",tipId : "ServDOETip",contentClass:"ServDOEContent"},
		{ name:"ICard", 	value:3, checkboxId : "ICardsCheckBox", tipId : "ICardsTip", contentClass:"ICardsContent"}
	];
	var val = $("#mstrProdOut").val();
	for (var i = 0; i < prodList.length; i++) {
		$("#" + prodList[i].checkboxId).unbind("click");
		if (val.indexOf(prodList[i].value) == -1) {
			$("#" + prodList[i].checkboxId).click(function() {return false;});
			$("#" + prodList[i].checkboxId).attr("checked", false);
			$("." + prodList[i].contentClass).css("display", "none");
			$("#" + prodList[i].tipId).css("display", "");
		} else {
			$("#" + prodList[i].checkboxId).click(function(ckId, contId) {
					 return function(){
						uam.MPCB.isChecked(ckId, contId);
					 }
			}(prodList[i].checkboxId, prodList[i].contentClass));
			$("#" + prodList[i].tipId).css("display", "none");
		}
	}
}

/*******************************************************************************
 * Validation  Block
 ******************************************************************************/

uam.vld.validate = function () {
	var sessionState = null;
	if(typeof(microstrategy) != 'undefined'){
		sessionState = String(microstrategy.sessionState);
	}
	
	$("#parForm").validationEngine('attach', {
		autoPositionUpdate: true,
		
		onValidationComplete: function(form, status) {
			if (status) {
				uam.utils.startProgress();
				$(form).ajaxSubmit({
					url:  "./taskProc",
					type: 'POST',
					data: {
						taskId : "EPATask",
						taskEnv : "xhr",
						taskContentType : "json",
						TaskSubID : "RegisterUserProfile",
						session : sessionState,
						rand : (new Date()).getTime()
					},
					cache: "false",
					dataType: "json",
					async: true, //set to false in case we want it to wait
					success: function(data) {
						
						console.log("response data: " + data);
						
						if (data["status"] == 200) {
							//location.href = "../plugins/UAM/jsp/Exception-Access_Confirmation.jsp";
							alert("success");
							location.href = "mstrWeb?pg=EPACnf";
						} else {
							data["data"] ? alert("error: " + data["data"]) : alert("ERROR!!");
						};
						uam.utils.stopProgress();
					} ,
					error: function (XMLHttpRequest, textStatus, errorThrown) {
				        console.log("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
				        uam.utils.stopProgress();
				    }	
			    });
				
			} else {
				console.log("The form '" + form.attr("id") + "' status is: " + status + ", it will not submit");
			}
			
		}
	
	});
			
}

uam.vld.validateMstrProd = function (field, rules, i, options){
	
	if (field.prop("options").length == 0) {
		if (rules.indexOf("required") == -1) {
			rules.push("required");
		}
		return options.allrules.required.alertTextCheckboxMultiple;
	} else {
		var i = rules.indexOf("required");
		if (i != -1) {
			rules.splice(i, 1);
		}
		return false; // return false or undefined or nothing 
	}
}
uam.vld.validateSpecialChars = function(field, rules, i, options) {
	var specialChars = ['-', '(', ')', ' '];
	var value = uam.utils.trim(field.val());
	
	if (!value) return ; // return false or undefined
	
	for (var i = 0; i < specialChars.length; i++) {
		if (value.indexOf(specialChars[i]) != -1 ) {
			return "Please remove '-', '(', ')', or space ";	
		}
	}
}

uam.vld.validateSingleQuote = function (field, rules, i, options) {
	return (field.val().indexOf("'") == -1) ? false : "Please remove single quotes";
}

uam.vld.validateIAMNumber = function (field, rules, i, options) {
	if (field.val().length != 10) {
		return "* Invalid IAM Number";
	}
	if (!(/^[\-\+]?\d+$/).test(field.val())){
		return "* Invalid IAM Number";
	} 
	if (field.val() == "0000000000" || field.val() == "1111111111") {
		return "* Invalid IAM Number";
	}
}

/*******************************************************************************
 * Task Definition Block
 ******************************************************************************/
uam.task.TNS = {
	LoadUP : "LoadUP",
	LoadMarcGroup : "LoadMarcGroup",// loadFuncGroupByGroupName
	LoadPrivilegesGroup : "LoadPrivilegesGroup",//loadFuncGroupByGroupName
	LoadAllProjects : "LoadAllProjects",
	ExtractMarcUserGroup : "ExtractMarcUserGroup",
	LoadGEOCounrty : "LoadGEOCounrty",
	LoadGEORegion : "LoadGEORegion",
	
	InitCustomerService : "InitCustomerService",
	InitUserType : "InitUserType",
	InitUnEditPII : "InitUnEditPII",
	InitGeneralInfo : "InitGeneralInfo",
	InitMstrProd : "InitMstrProd",
	InitGmaps : "InitGmaps",
	InitMarcFuncGroup : "InitMarcFuncGroup",
	InitOptBlue : "InitOptBlue",
	InitMarcSharedReports : "InitMarcSharedReports",
	InitRegionAndCountryDialog : "InitRegionAndCountryDialog"
	
}
// load user profile (from cookie)
uam.task.loadUP = function(hostTask) {
	
	var data = {};
	
	if ($.cookie("TransferData") != null && $.cookie("TransferData") != "" && $.cookie("TransferData") != " ") {
		
		var alldata = $.cookie("TransferData").split("|");
		var temp = null;
		// User ID and name
		data["USER_ID"] = alldata[0].replace("\"","").replace("employeenumber: ","");
	    data["USER_1ST_NM"] =  alldata[1].replace("givenName: ","");
	    data["USER_LST_NM"] =  alldata[2].replace("sn: ","");
	    temp = alldata[3].replace("axppmiddlename:","");
	    data["USER_MI_TX"] = (temp == "null") ? "" : temp;
	    
	    // Department code and name 
	    data["DEPT_ID"] =  alldata[4].replace("axppdepartment: ","");
	    data["DEPT_NM"] =  alldata[4].replace("axppdepartment: ","");
	    
	    if (data["DEPT_ID"] && data["DEPT_ID"].length > 7){
	    	data["DEPT_ID"] = data["DEPT_ID"].substring(0, 7);
	    }
	    
	    //Business code and name
	    temp = alldata[5].replace("axppbusiness_cd:","");
	    data["AMEX_BUS_CD"] = (temp == "null") ? "" :temp;
	    data["AMEX_BUS_DS_TX"] =  alldata[6].replace("axppbusiness_descr: ","");
	    
	    // Cost center	    
	    data["COST_CTR_CD"] =  alldata[7].replace("axppcc-cd: ","");
	    
	    // user email
	    data["USER_EMAIL_AD_TX"] =  alldata[8].replace("mail: ","");
	    
	    // This variable is the manager id?
	    //var axppmanagerid = alldata[9];
	    
	    // Amex unit code and desc
		data["AMEX_UNIT_CD"] =  alldata[10].replace("axppunit_cd: ","");
	    data["AMEX_UNIT_DS_TX"] =  alldata[11].replace("axppunit_descr: ","");
	    
	    // amexWebId
	    data["WORKFORCE_MBR_ID"] =  alldata[12].replace("\"","").replace("uid: ","");
	    
	} else {
		
		//hostTask.error();
		console.log("error-message: TransferData cookie is empty or unavailable");
		
		/* *************************/
		/* below is the test codes */
		/* *************************/
		
		// User ID and name
		data["USER_ID"] = "";
	    data["USER_1ST_NM"] = "";
	    data["USER_LST_NM"] = "";
	    data["USER_MI_TX"] = "";
	    // Department code and name
	    data["DEPT_ID"] =  "";
	    data["DEPT_NM"] =  "";
	    //Business code and name
	    data["AMEX_BUS_CD"] = "";
	    data["AMEX_BUS_DS_TX"] = "";
	    // Cost center
	    data["COST_CTR_CD"] = "";
	    // user email
	    data["USER_EMAIL_AD_TX"] = "";
	    // Amex unit code and desc
		data["AMEX_UNIT_CD"] =  "";
	    data["AMEX_UNIT_DS_TX"] =  "";
	    // amexWebId
	    data["WORKFORCE_MBR_ID"] = "";
		
	  }
		
	data["USER_ACSS_TYPE_CD"] =  "EC";

	var defVal = "";
	data["ACSS_RSN_TX"] = defVal;
    data["DAYS_DIFF"] = defVal;
    data["USER_STA_CD"] = defVal;
    data["USER_TYPE_CD"] = defVal;// 01 or 02
    data["USER_ADMIN_STA_CD"] = defVal;
    data["USER_CMPL_PHONE_NO"] = defVal;
    data["NDA_TS"] = defVal;
    data["CLM_GLBL_ACS_IN"] = defVal;
    data["WORKFORCE_MBR_MAN_1ST_NM"] = defVal;
    data["WORKFORCE_MBR_MAN_LST_NM"] = defVal;
    data["WORKFORCE_MBR_MAN_MI_TX"] = defVal;
    data["WORKFORCE_MBR_MAN_EMAIL_AD_TX"] = defVal;
    data["SEC_XCPT_END_DT"] = defVal;
    data["FUNC_GRP_ROLE_ID"] = defVal;
    data["FUNC_GRP_ROLE_NM"] = defVal;
    data["VP_NM"] = defVal;
    data["LIF_GLBL_ACS_IN"] = defVal;
	
	hostTask.setData(data);
	hostTask.complete();
		
}

/*
 * Load function group by group name (from MD)
 */
uam.task.loadFuncGroupByGroupName = function(hostTask) {
	var userId = hostTask.getData(uam.task.TNS.LoadUP)["USER_ID"];
	var groupName = hostTask.getParameter("groupName");
	var params = {
		'taskId' : 'EPATask',
		'TaskSubID' : 'LoadSecurityGroupByGroupName',
		'userId'  : userId,
		'groupName' : groupName
	};
	uam.utils.callTask(params, function(responseData) {
		eval("var responseContext=" + responseData);
		//console.log("** Get Security Data:");
		//console.log(responseData);
		//console.log(responseContext.data);
		if (responseContext["status"] == uam.utils.responseCode.OK) {
			
			hostTask.setData(responseContext.data);
			hostTask.complete();
		} else {
			hostTask.error();
			console.log(hostTask.getID() +" error!");
			console.log("error-code: " + responseContext.status);
			console.log("error-message: " + responseContext.data);
		}
	});
				
}
//load all project info
uam.task.loadAllProjects = function(hostTask) {
	uam.utils.callTask({ taskId:"EPATask", TaskSubID: "LoadAllProjects" }, function(data) {
		
		eval("responseContent = " + data);
		
		if (responseContent["status"] == uam.utils.responseCode.OK) {
			hostTask.setData(responseContent.data);
			hostTask.complete();
		} else {
			hostTask.error();
			console.log(hostTask.getID() +" error!");
			console.log("error-code: " + responseContext.status);
			console.log("error-message: " + responseContext.data);
		}
		
	});
}

// extract "MARC User group"
uam.task.extractMarcUserGroup = function(hostTask) {
	
	var marcGroup = hostTask.getData(uam.task.TNS.LoadMarcGroup);
	
	// find "MARC Security View"
	var marcUserGroup = uam.task.findGroup(marcGroup, "MARC User group");
	// console.log(marcScyViewGroup);
	
	if (marcUserGroup != null && marcUserGroup.children.length > 0) {
		hostTask.setData(marcUserGroup);
		hostTask.complete();
	} else {
		hostTask.error();
		console.log(hostTask.getID() +" error!");
		console.log("error-message: the target group 'MARC Security View' not found");
	}
	
}

uam.task.findGroup = function(sourceGroup, targetGroupName) {
	
	if (sourceGroup == null || targetGroupName == null) {
		//console.log("Error: parameters is invalid. sourceGroup: " + sourceGroup + ", targetGroupName: " + targetGroupName);
		return null;
	}
	
	//console.log(" -- " + sourceGroup.groupName);
	if (sourceGroup.groupName ==  targetGroupName) {
		//console.log("found the target group.");
		return sourceGroup;
	}
	
	var targetGroup = null;
	for (var i = 0; i < sourceGroup.children.length; i++) {
		targetGroup = uam.task.findGroup(sourceGroup.children[i], targetGroupName);
		if (targetGroup != null) {
			break;
		}
	}
	return targetGroup;
}

uam.task.load = function(hostTask) {
	var params = hostTask.getParameters() || {};
	params['taskId'] = params['taskId'] || 'EPATask';
	
	var debug = hostTask.getParameter('debug');
	
	uam.utils.callTask(params, function(responseData) {
		eval("var responseContext=" + responseData);
		
		if (debug) {
			console.log("uam.task.load -> " + hostTask.getID());
			console.log(responseData);
		}
		
		if (responseContext["status"] == uam.utils.responseCode.OK) {
			
			hostTask.setData(responseContext.data);
			hostTask.complete();
		} else {
			hostTask.error();
			console.log(hostTask.getID() +" error!");
			console.log("error-code: " + responseContext.status);
			console.log("error-message: " + responseContext.data);
		}
	});
}

//init customer service
uam.task.initCustomerService = function(hostTask) {
	var userProfile = hostTask.getData(uam.task.TNS.LoadUP);
	var cd = parseInt(userProfile["USER_TYPE_CD"]);
	
	// The checkbox is readonly and If customer is a manager then check it
	// '01' or '1' represent a manager
	if (cd == 1) {
		$("input[name=custmServs]").attr("checked", true);
	}
	$("input[name=custmServs]").click(function(){return false;});
	
	// Notify the task manager that this task has ended
	hostTask.complete();
}
// init user type
uam.task.initUserType = function(hostTask) {
	var group = hostTask.getData(uam.task.TNS.LoadPrivilegesGroup);
	
	var root = $(".userTypeCont").empty();
	
	var WORD = " User";
	for (var i = 0; i < group.children.length; i++) {
		var g = group.children[i];
		var itemName = "usrTpRadio";
		var itemId = itemName + "_" + g.groupID;
		var itemVal = g.groupName; // g.groupID;
		var itemLab = uam.utils.endWith(g.groupName, WORD) 
			? g.groupName.substring(0, g.groupName.length - WORD.length) 
			: g.groupName;
		
		$("<input type='radio'/>").attr("id", itemId).attr("name", itemName).val(itemVal).appendTo(root);
		$("<label/>").attr("for", itemId).append(itemLab).appendTo(root);
		//<input type="radio" name="usrTpRadio"><label for="usrTpRadio">Analyst</label>
		
	}
	// Notify the task manager that this task has ended
	hostTask.complete();
}

uam.task.initUnEditPII = function(hostTask) {
	var cache = hostTask.getData(uam.task.TNS.LoadUP);
	
	$(".unEditPII .firstName").html(cache["USER_1ST_NM"]);
	$(".unEditPII .amexWebId").html(cache["WORKFORCE_MBR_ID"]);
	$(".unEditPII .accType").html(cache["USER_ACSS_TYPE_CD"]);//XXX accType and accStatus have the same value?
	
	$(".unEditPII .midName").html(cache["USER_MI_TX"]);
	$(".unEditPII .accStatus").html(cache["USER_ACSS_TYPE_CD"]);//XXX
	$(".unEditPII .empId").html(cache["USER_ID"]);
	
	$(".unEditPII .lastName").html(cache["USER_LST_NM"]);
	$(".unEditPII .costCen").html(cache["COST_CTR_CD"]);
	$(".unEditPII .accStatusDate").html(uam.utils.date2String(new Date()));
	
	// Notify the task manager that this task has ended
	hostTask.complete();
}
// Initialize the "User Profile General Information" block
uam.task.initGeneralInfo = function(hostTask) {
	
	var upData = hostTask.getData(uam.task.TNS.LoadUP);// user profile
	//empId
	$("input[name='empId']").val(upData["USER_ID"]);
	//amexWebId
	$("input[name='amexWebId']").val(upData["WORKFORCE_MBR_ID"]);
	//firstName
	$("input[name='firstName']").val(upData["USER_1ST_NM"]);
	//midName
	$("input[name='midName']").val(upData["USER_MI_TX"]);
	//lastName
	$("input[name='lastName']").val(upData["USER_LST_NM"]);
	//accType
	//$("input[name='accType']").val(upData["USER_ACSS_TYPE_CD"]);
	// Access End Date
	$("#accEndDate").datebox().datebox('setValue', '12/31/9999');
	
	//Department ID
	$("input[name='deptId']").val(upData["DEPT_ID"]);
	//AMEX Unit Code
	$("input[name='amexUnitCD']").val(upData["AMEX_UNIT_CD"]);
	//Department Description
	$("input[name='deptDesc']").val(upData["DEPT_NM"]);
	//AMEX Unit Description
	$("input[name='amexUnitDesc']").val(upData["AMEX_UNIT_DS_TX"]);
	//Business Unit Code
	$("input[name='bussUnitCD']").val(upData["AMEX_BUS_CD"]);
	//Cost Center
	$("input[name='costCenter']").val(upData["COST_CTR_CD"]);
	//Business Unit Description
	$("input[name='bussUnitDesc']").val(upData["AMEX_BUS_DS_TX"]);
	//Phone #
	$("input[name='phone']").val(upData["USER_CMPL_PHONE_NO"]);
	//Email Address
	$("input[name='emailAddr']").val(upData["USER_EMAIL_AD_TX"]);
	//Manager Email Address
	$("input[name='mgrEmailAddr']").val(upData["WORKFORCE_MBR_MAN_EMAIL_AD_TX"]);
	//Manager First Name
	$("input[name='mFName']").val(upData["WORKFORCE_MBR_MAN_1ST_NM"]);
	//VP Name
	$("input[name='VPName']").val(upData["VP_NM"]);
	//Manager Middle Initial
	$("input[name='mMidInit']").val(upData["WORKFORCE_MBR_MAN_MI_TX"]);
	//Reason For Access
	$("input[name='reason4Accs']").val(upData["ACSS_RSN_TX"]);
	//Manager Last Name
	$("input[name='mLName']").val(upData["WORKFORCE_MBR_MAN_LST_NM"]);
	
	// Notify the task manager that this task has ended
	hostTask.complete();
}

//Initialize the "MicroStrategy Product Select*" view block
uam.task.initMstrProd =  function(hostTask) {
	var projList = hostTask.getData(uam.task.TNS.LoadAllProjects);// all projects
	
	for (var i = 0; i < projList.length; i++) {
		// [{  "MS_PROJ_ID": 1, "MS_PROJ_NM": "MARC", "CREAT_TS": "2009-06-03 05:58:24.203" }]
		$("<option/>")
		.val(projList[i]["MS_PROJ_ID"])
		.dblclick(function(){uam.ShoppingCart.select('mstrProdAvl', 'mstrProdSel', 'mstrProdOut', uam.productChanged);})
		.append(uam.utils.trim(projList[i]["MS_PROJ_NM"], ""))
		.appendTo("#mstrProdAvl");
	}
	uam.productChanged();
	
	hostTask.complete();
}

uam.task.initGmaps = function (hostTask) {
	var marcUserGroup = hostTask.getData(uam.task.TNS.ExtractMarcUserGroup);
	var children = marcUserGroup.children;

	var KEY = "MARC GMAPS ";
	var itemParent = $(".gmapsCont").empty();
	var itemName = "gmapsRadio";
	
	for (var i = 0; i < children.length; i++) {
		if (uam.utils.startWith(children[i].groupName, KEY)) {
			var itemId = itemName + "_" + children[i].groupID;
			var itemVal = children[i].groupName;
			var itemLab = children[i].groupName.substring(KEY.length);
			
			$("<input type='radio' />").attr("name", itemName).attr("id", itemId ).val(itemVal).appendTo(itemParent);
			$("<label/>").attr("for", itemId).append(itemLab).appendTo(itemParent);
			$("<br/>").appendTo(itemParent);
			
		}
	}

	$("<label for='" + itemName + "_-1'>No Access</label><br>").prependTo(itemParent);
	$("<input type='radio' value='-1'/>").attr("name", itemName).attr("checked", true).attr("id", itemName + "_-1").prependTo(itemParent);
	// Notify the task manager that this task has ended
	hostTask.complete();
}

uam.task.initMarcFuncGroup = function (hostTask) {
	var marcUserGroup = hostTask.getData(uam.task.TNS.ExtractMarcUserGroup);
	var children = marcUserGroup.children;
	
	var KEY = "MARC GMAPS ";
	var KEY2 = "MARC OptBlue";
	var KEY3 = "MARC ";
	
	var itemParent = $(".marcFunCont").empty();

	for (var i = 0; i < children.length; i++) {
		if (uam.utils.startWith(children[i].groupName, KEY) || children[i].groupName == KEY2) {
			continue;
		}
		
		var itemId = "marcFuncRadio" + children[i].groupID;
		var itemName = "marcFuncRadio";
		var itemVal = children[i].groupName;
		var itemLab = (uam.utils.startWith(children[i].groupName, KEY3)) 
			? children[i].groupName.substring(KEY3.length) 
			: children[i].groupName; 
		
		$("<input type='checkbox' />").attr("name", itemName).attr("id", itemId ).val(itemVal).appendTo(itemParent);
		$("<label/>").attr("for", itemId).append(itemLab).appendTo(itemParent);
		$("<br/>").appendTo(itemParent);
		
	}
	
	// Notify the task manager that this task has ended
	hostTask.complete();
}

uam.task.initOptBlue = function (hostTask) {
	var marcUserGroup = hostTask.getData(uam.task.TNS.ExtractMarcUserGroup);
	
	var KEY = "MARC OptBlue";
	var KEY2 = "Opt Blue "; 
	
	// find the 'MARC OptBlue' group
	for (var i = 0; i < marcUserGroup.children.length; i++) {
		if (marcUserGroup.children[i].groupName == KEY) {
			marcOptBlueGroup = marcUserGroup.children[i];
			break;
		}
	}
	
	if (!marcOptBlueGroup){
		console.log("WARN: the group 'MARC OptBlue' not found.");
		return;
	}
	
	var itemParent = $(".optBlueCont").empty();
	var itemName = "optBlueRadio";
	var children = marcOptBlueGroup.children;
	
	for (var i = 0; i < children.length; i++) {
		//console.log("--"+children[i].groupName);
		var itemId = "optBlueRadio" + children[i].groupID;
		var itemVal = children[i].groupName;
		var itemLab = uam.utils.startWith(children[i].groupName, KEY2) ? children[i].groupName.substring(KEY2.length) : children[i].groupName; 
		
		$("<input type='radio' />").attr("name", itemName).attr("id", itemId ).val(itemVal).appendTo(itemParent);
		$("<label/>").attr("for", itemId).append(itemLab).appendTo(itemParent);
		$("<br/>").appendTo(itemParent);
		
	}
	
	$("<label for='" + itemName + "_-1'>No Access</label><br>").prependTo(itemParent);
	$("<input type='radio' value='-1'/>").attr("name", itemName).attr("checked", true).attr("id", itemName + "_-1").prependTo(itemParent);
	
	// Notify the task manager that this task has ended
	hostTask.complete();
}
// Shared Reports Initialization 
uam.task.initMarcSharedReports = function(hostTask) {
	var marcGroup = hostTask.getData(uam.task.TNS.LoadMarcGroup);
	var sharedRptGrp = uam.task.findGroup(marcGroup, "MARC Shared Report Security View");
	
	if (!sharedRptGrp || !sharedRptGrp.children) {
		console.log("No data of Shared Reports.");
		hostTask.error();
		return;
	}
	
	var root = $(".shdRptCont table tbody").empty();
	var oriVal = $("<input type='hidden' name='ori_shdRptVal'>").appendTo(".shdRpt");
	var chgName = $("<input type='hidden' name='shdRptName'>").appendTo(".shdRpt");
	for (var i = 0; i < sharedRptGrp.children.length; i++) {
		
		var trNode = $("<tr/>").appendTo(root);
		var result = uam.task.renderSharedReportsRow(trNode, sharedRptGrp.children[i], ["shFderNm", "", "", "midFrm"]);
		if (result && result.name) {
			chgName.val(chgName.val() + result.name + "," );
			result.value && oriVal.val(oriVal.val() + result.value + ",");
		}
		
		i++;
		result = uam.task.renderSharedReportsRow(trNode, sharedRptGrp.children[i], ["shFderNm", "", "", ""]);
		if (result && result.name) {
			chgName.val(chgName.val() + result.name + "," );
			result.value && oriVal.val(oriVal.val() + result.value + ",");
		}
		
	}
	//console.log(chgName.val());
	//console.log(oriVal.val());
	
	// Notify the task manager that this task has ended
	hostTask.complete();
}
/*
 * 
 * @param {Object} parentNode tr node (jQuery object)
 * @param {Object} rptGrp the sub security group of shared reports (JSON Object)
 * @param {Array<String>} styles an array of length 4 
 * 
 * @return {Map<String,String>} return the radio name and the original value (e.g. {name:'radio_name', value:"original value"}) 
 */
uam.task.renderSharedReportsRow = function(parentNode, rptGrp, styles) {

	if (!rptGrp) {
		parentNode.append("<td/><td/><td/><td/>");
		return null;
	}
	
	var KEY_MARC = "MARC ";
	var KEY_R = "(Read Only)";
	var KEY_RW = "(Read/Write)";
	
	var itemLab = uam.utils.startWith(rptGrp.groupName, KEY_MARC) 
		? rptGrp.groupName.substring(KEY_MARC.length) 
		: rptGrp.groupName;
	var itemName = "shdRpt_" + rptGrp.groupID;
	//var itemVal = rptGrp.groupName;
	var itemValNoAccess = "-1";
	
	var readonly = false;
	var readWrite = false;
	var rVal = null;
	var rwVal = null;
	
	var oriVal = null;
	
	for (var i = 0; i < rptGrp.children.length; i++) {
		var subGrp = rptGrp.children[i];
		if (uam.utils.endWith(subGrp.groupName, KEY_R)) {
			if (subGrp.contains == true) {
				readonly = true;
				oriVal = subGrp.groupName;
			}
			rVal = subGrp.groupName;
		} else if (uam.utils.endWith(subGrp.groupName, KEY_RW)) {
			if (subGrp.contains == true) {
				readWrite = true;
				oriVal = subGrp.groupName;
			}
			rwVal = subGrp.groupName;
		}
		
	}
	var noAccess = (!readonly && !readWrite);
	
	//console.log("Label: " + itemLab + ", no-access: " + noAccess + ", readonly: " + readonly + ", read-write: " + readWrite);
	
	// add a label
	var tdIdx = 0;
	var td0 = $("<td/>").append(itemLab).addClass((styles && styles[tdIdx]) ? styles[tdIdx] : "").appendTo(parentNode);
	
	// add a no access radio button
	tdIdx++;
	var td1 = $("<td/>").addClass((styles && styles[tdIdx]) ? styles[tdIdx] : "").appendTo(parentNode);
	$("<input type='radio'/>").attr("name", itemName).attr("checked", noAccess).val(itemValNoAccess).appendTo(td1);
	
	// add a read-only radio button
	tdIdx++;
	var td2 = $("<td/>").addClass((styles && styles[tdIdx]) ? styles[tdIdx] : "").appendTo(parentNode);
	$("<input type='radio'/>").attr("name", itemName).attr("checked", readonly).val(rVal).appendTo(td2);
	
	// add a read-only radio button
	tdIdx++;
	var td3 = $("<td/>").addClass((styles && styles[tdIdx]) ? styles[tdIdx] : "").appendTo(parentNode);
	$("<input type='radio'/>").attr("name", itemName).attr("checked", readWrite).val(rwVal).appendTo(td3);
	
	return {name : itemName, value : oriVal};
}

uam.task.initRegionAndCountryDialog = function(hostTask) {
	
	var countryList = hostTask.getData(uam.task.TNS.LoadGEOCounrty);
	var regionList = hostTask.getData(uam.task.TNS.LoadGEORegion);
	var userCountryList = [];
	var userRegionList = [];

	var countryRoot = $(".rcCountry").empty();
	uam.task.initRegionAndCountryDialog_country(countryRoot, countryList, userCountryList);
	
	var regionRoot = $(".rcRegion").empty();
	var columnCount = 6;
	uam.task.initRegionAndCountryDialog_region(regionRoot, regionList, userRegionList, columnCount );
	
	hostTask.complete();
}
/**
 * Initialize the country section of the 'Region/Country' dialog
 *  
 * @param {Object} root (jQuery Object)
 * @param {Array<Object>} countryList
 * @param {Array<Object>} userCountryList 
 */
uam.task.initRegionAndCountryDialog_country = function(root, countryList, userCountryList){
	/*
	The object in the country list: { "GEO_AREA_ID": 346, "GEO_AREA_NM": "US", }
    The object in the user country list: { "WORKFORCE_MBR_ID": "abhatna1", "CTRY_NM": ""}
    UI: var root = $(".rcCountry");
	    <div class="rcCountry">
			<span><label for="us">US</label><input type="checkbox" name="us"/></span>
			<span><label for="us">US</label><input type="checkbox" namem="us"/></span>
		</div>
	*/
	var dict = {};
	for (var ui = 0; ui < userCountryList.length; ui++) {
		var countryName = uam.utils.trim(userCountryList[ui]["CTRY_NM"]);
		if (countryName) {
			dict[countryName] = true;
		}
	}
	//dict["US"] = true;//for test
	
	for (var i = 0; i < countryList.length; i++) {
		var itemLab = uam.utils.trim(countryList[i]["GEO_AREA_NM"]);
		var itemVal = itemLab;
		var itemId = "rc_ctry_" + countryList[i]["GEO_AREA_ID"];
		var itemName = "rcCtry";
		var itemChecked = dict[itemLab] ? true : false;
		
		var span = $("<span/>").appendTo(root);
		$("<label/>").attr("for", itemId).append(itemLab).appendTo(span);
		$("<input type='checkbox'/>").attr("id", itemId).attr("name", itemName)
			.attr("checked", itemChecked).val(itemVal).appendTo(span);
	}
}
/**
 * Initialize the region section of the 'Region/Country' dialog
 *  
 * @param {Object} root (jQuery Object)
 * @param {Array<Object>} regionList
 * @param {Array<Object>} userRegionList
 * @param {int} columnCount
 */
uam.task.initRegionAndCountryDialog_region = function(root, regionList, userRegionList, columnCount){
	/*
	region { "GEO_AREA_ID": 261, "GEO_AREA_NM": "ZZ AMEX USE UNITED KINGDOM" }
	user region: { "WORKFORCE_MBR_ID": "abhatna1   ", "RGN_ABBR_NM": "" }
    */
	
	var dict = {};
	for (var ui = 0; ui < userRegionList.length; ui++) {
		var regionName = uam.utils.trim(userRegionList[ui]["RGN_ABBR_NM"]);
		if (regionName) {
			dict[regionName] = true;
		}
	}
	//dict["AFGHANISTAN"]=true;//for test
	
	var extraRows = (regionList.length % columnCount);
	var rowCount =  parseInt(regionList.length / columnCount);
	//console.log("regionList.length: " + regionList.length + ", columnCount: " + columnCount);
	//console.log("extraRows:"+extraRows+", rowCount"+rowCount);
	var offset = 0;
	for (var i = 0; i < columnCount; i++) {
		var regionColumn = null;
		if (i < columnCount - 1) {
			regionColumn = $("<div class='rcRegionCont normal'/>").appendTo(root); 
		} else {
			regionColumn = $("<div class='rcRegionCont last' />").appendTo(root); 
		}
		var count = rowCount + ((extraRows-- > 0) ? 1 : 0);
		//console.log(i + ", " + count);
		for (var j = 0; j < count; j++, offset++) {
			//console.log("->" + offset);
			var itemTip = uam.utils.trim(regionList[offset]["GEO_AREA_NM"]);
			var itemLab = (itemTip.length <= 15) ? itemTip : itemTip.substring(0,15) + "...";
			var itemVal = itemTip;
			var itemId = "rc_rgn_" + regionList[offset]["GEO_AREA_ID"];
			var itemName = "rcRgn";
			var itemChecked = dict[itemTip] ? true : false;
			
			$("<input type='checkbox' />").attr("id", itemId).attr("name", itemName)
				.attr("checked", itemChecked).val(itemVal).appendTo(regionColumn);
				
			$("<label/>").attr("for", itemId).attr("title", itemTip).append(itemLab).append("<br>")
				.appendTo(regionColumn);
		}
	}
	
}

/*********************************************
 * Initialize Pre-Approved Registration Page
 *********************************************/
$(document).ready(function(){
	
	uam.utils.startProgress();
	
	var TM = new org.snake.schedule.TaskManager();
	var F = org.snake.schedule.TaskFactory;
	var T = uam.task;
	var TNS = uam.task.TNS;

	/* ******************************/
	/* Data Loading Block           */
	/* ******************************/
	
	// load user profile from the cookies
	var loadUP = F.createTask(TNS.LoadUP, TM, T.loadUP);
	
	// Load MARC Security Groups
	var loadMarcGroup = F.createTask(TNS.LoadMarcGroup, TM, T.loadFuncGroupByGroupName)
		.addParameter("groupName", "MARC")
		.addDependency(loadUP.getID());
	
	// Load Privileges Security Groups
	var loadPrivilegesGroup = F.createTask(TNS.LoadPrivilegesGroup, TM, T.loadFuncGroupByGroupName)
		.addParameter("groupName", "Privileges")
		.addDependency(loadUP.getID()) 
		.addDependency(loadMarcGroup.getID());// avoid the access limits
		
	// Load All the Projects
	var loadAllProjects = F.createTask(TNS.LoadAllProjects, TM, T.loadAllProjects);
	
	// Extract the MARC User Groups
	var extractMarcUserGroup = F.createTask(TNS.ExtractMarcUserGroup, TM, T.extractMarcUserGroup)
		.addDependency(loadMarcGroup.getID());
	
	// Load Countries
	var loadGEOCounrty = F.createTask(TNS.LoadGEOCounrty, TM, T.load)
		.setParameters({TaskSubID : "LoadGEOCounrty"/*, debug : true*/});
		
	// Load GEO Region
	var loadGEORegion = F.createTask(TNS.LoadGEORegion, TM, T.load)
		.setParameters({TaskSubID : "LoadGEORegion"/*, debug : true*/});
		
	/* ******************************/	
	/* Control Initialization Block */	
	/* ******************************/
	
	// Customer Service
	F.createTask(TNS.InitCustomerService, TM, T.initCustomerService)
		.addDependency(loadUP.getID());
	
	// User Type
	F.createTask(TNS.InitUserType, TM, T.initUserType)
		.addDependency(loadPrivilegesGroup.getID());

	// Readonly User Info
	F.createTask(TNS.InitUnEditPII, TM, T.initUnEditPII)
		.addDependency(loadUP.getID());
		
	// User Profile General Information
	F.createTask(TNS.InitGeneralInfo, TM, T.initGeneralInfo)
		.addDependency(loadUP.getID());
	
	// MicroStrategy Product Select
	F.createTask(TNS.InitMstrProd, TM, T.initMstrProd)
		.addDependency(loadAllProjects.getID());
		
	// GMAPS
	F.createTask(TNS.InitGmaps, TM, T.initGmaps)
		.addDependency(extractMarcUserGroup.getID());
	
	// MARC Functional Group
	F.createTask(TNS.InitMarcFuncGroup, TM, T.initMarcFuncGroup)
		.addDependency(extractMarcUserGroup.getID());	
		
	// Opt Blue
	F.createTask(TNS.InitOptBlue, TM, T.initOptBlue)
		.addDependency(extractMarcUserGroup.getID());
	
	// Shared Reports dialog
	// @unused This requirement changed
	/*F.createTask(TNS.InitMarcSharedReports, TM, T.initMarcSharedReports)
		.addDependency(loadMarcGroup.getID());*/
	
	// Country/Region dialog
	F.createTask(TNS.InitRegionAndCountryDialog, TM, T.initRegionAndCountryDialog)
		.addDependency(loadGEOCounrty.getID())
		.addDependency(loadGEORegion.getID());
		
	TM.addListener("completed", uam.utils.stopProgress);
	
	TM.debug(false);
	TM.start();
	
	uam.MPCB.isChecked("marcCheckBox", "marcContent");
	uam.MPCB.isChecked("ICardsCheckBox", "ICardsContent");
	uam.MPCB.isChecked("servDOECheckBox", "ServDOEContent");
	
	uam.vld.validate();
	
	console.log("initialization finished");
});
